package me.keiwu.user.util;

import me.keiwu.pub.data.ResponseV2;
import me.keiwu.user.rpc.LogErrorRpc;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;

/**
 * Created by kei on 29/12/2017.
 */
@Component
@ControllerAdvice
public class ExceptionUtil {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionUtil.class);


    @Autowired
    private LogErrorRpc logErrorRpc;


    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public ResponseV2 defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        String uri = req.getRequestURI();
        String msg = e.getMessage();
        logger.error("GlobalExceptionHandler uri={}, e: ", uri, e);
        this.logError(ExceptionUtil.class, "defaultErrorHandler", uri, msg);
        return ResponseV2.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), "网络不给力，请稍后再试");
    }



    public void logError(Class clazz, String funcName, String msg) {
        this.logError(clazz, funcName, null, msg);
    }

    public void logError(Class clazz, String funcName, String requestUri, String msg) {
        try {
            String localIp = InetAddress.getLocalHost().getHostAddress();
            if (StringUtils.isNotBlank(msg) && msg.length() >= 255) {
                msg = msg.substring(0, 254);
            }
            logErrorRpc.logError(requestUri, localIp, clazz.getName(), funcName, msg);
        } catch (Exception e) {
            logger.error("error when dealing the exception!", e);
        }
    }

}
